using Digitalmes.Application.Sys.Users;
using Digitalmes.Application.Sys.Users.Commands;
using Digitalmes.Application.Sys.Users.Queries;

namespace Digitalmes.WebApi.Endpoints.Sys;

/// <summary>
/// 账号信息终结点。
/// </summary>
public sealed class AccountEndpoint : EndpointGroupBase
{
    public override void Map(WebApplication app)
    {
        app.MapGroup(this, "sys", "account")
            .RequireAuthorization()
            .MapGet(GetUserPagedListAsync, "list-page")
            .MapGet(GetUserByIdAsync, "{id}")
            .MapPost(CreateUserAsync)
            .MapPut(UpdateUserAsync, "{id}")
            .MapPut(ResetPasswordUserAsync, "reset-password")
            .MapPut(ChangeStatusUserAsync, "change-status")
            .MapPost(GrantRolesToUserAsync, "grant-roles")
            .MapDelete(DeleteUserAsync, "{id}");
    }

    [EndpointDescription("分页查询用户")]
    public async Task<IApiResult> GetUserPagedListAsync(ISender sender, [AsParameters] GetUserListWithPagedQuery query)
    {
        var result = await sender.Send(query);
        return result.ToApiResult();
    }

    [EndpointDescription("按 Id 查询用户")]
    public async Task<IApiResult> GetUserByIdAsync(ISender sender, long id)
    {
        var result = await sender.Send(new GetUserByIdQuery(id));
        return result.ToApiResult();
    }

    [EndpointDescription("创建用户")]
    public async Task<IApiResult> CreateUserAsync(ISender sender, SysUserDto dto)
    {
        var result = await sender.Send(new CreateUserCommand(dto));
        return result.ToApiResult();
    }

    [EndpointDescription("更新用户信息")]
    public async Task<IApiResult> UpdateUserAsync(ISender sender, long id, SysUserDto dto)
    {
        var result = await sender.Send(new UpdateUserCommand(id, dto));
        return result.ToApiResult();
    }

    [EndpointDescription("重置用户密码")]
    public async Task<IApiResult> ResetPasswordUserAsync(ISender sender, ResetPasswordCommand command)
    {
        var result = await sender.Send(command);
        return result.ToApiResult();
    }

    [EndpointDescription("更改用户启用状态")]
    public async Task<IApiResult> ChangeStatusUserAsync(ISender sender, ChangeUserStatusCommand command)
    {
        var result = await sender.Send(command);
        return result.ToApiResult();
    }

    [EndpointDescription("给用户分配角色")]
    public async Task<IApiResult> GrantRolesToUserAsync(ISender sender, GrantRolesToUserCommand command)
    {
        var result = await sender.Send(command);
        return result.ToApiResult();
    }

    [EndpointDescription("删除用户")]
    public async Task<IApiResult> DeleteUserAsync(ISender sender, long id)
    {
        var result = await sender.Send(new DeleteUserCommand(id));
        return result.ToApiResult();
    }
}
